package com.ybg.share.schedule;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ybg.framework.constant.RedisKey;

import com.ybg.framework.dto.AbstractJob;
import com.ybg.share.core.dbapi.entity.ShareFinancialYear;
import com.ybg.share.core.dbapi.entity.ShareStock;
import com.ybg.share.core.dbapi.entity.ShareStockDayK;
import com.ybg.share.core.dbapi.service.ShareFinancialYearService;
import com.ybg.share.core.dbapi.service.ShareStockDayKService;
import com.ybg.share.core.dbapi.service.ShareStockService;
import com.ybg.share.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@Component
public class RedisJob {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ShareStockDayKService shareStockDayKService;
    @Autowired
    ShareStockService shareStockService;


    /**
     * 最新日K放到redis中
     */
    @Scheduled(cron = "0 30 6 * * ?")
    public void pushLastDayKToRedis() {

        redisTemplate.opsForValue().getOperations().delete(RedisKey.LAST_DAY_K);
        try {
            //这里放业务代码;
            log.info("最新日K放到redis中 ");
            AtomicInteger undata = new AtomicInteger();
            QueryWrapper<ShareStock> stockWrapper = new QueryWrapper<>();
            stockWrapper.eq(ShareStock.STATUS, 1);
            List<ShareStock> shareStockList = shareStockService.list(stockWrapper);
            if (shareStockList.size() == 0) {
                return;
            }
            CountDownLatch latch = new CountDownLatch(shareStockList.size());
            for (ShareStock shareStock : shareStockList) {
                ThreadUtil.execute(new AbstractJob(shareStock) {

                    @Override
                    public void execute() {
                        ShareStockDayK maxDateByCode = shareStockDayKService.getLastDayKByCode(shareStock.getCode(), shareStock.getId());

                        if (maxDateByCode != null) {
                            maxDateByCode.setId(null);
                            redisTemplate.opsForSet().add(RedisKey.LAST_DAY_K, JSONObject.toJSONString(maxDateByCode));
                        } else {
                            undata.incrementAndGet();
                        }
                        latch.countDown();
                    }
                });//线程
            }
            try {
                latch.await();
            } catch (Exception e) {
                log.info("pushLastDayKToRedis 报错了{} ", e);
                e.printStackTrace();
            }
            System.out.println("股票数量" + shareStockList.size() + ",没有数据的数量" + undata.get());

        } catch (Exception ex) {
            //异常处理
            log.info("已被其他服务抢占锁{}", ex);
        } finally {

        }


    }

    @Autowired
    private ShareFinancialYearService shareFinancialYearService;

    /**
     * 财报净利润放到redis中
     */
    @Scheduled(cron = "0 30 10 * * ?")
    public void reflushFinancialYearToRedis() {

        int thisYear = DateUtil.thisYear();
        AtomicInteger undata = new AtomicInteger();
        QueryWrapper<ShareStock> stockWrapper = new QueryWrapper<>();
        stockWrapper.eq(ShareStock.STATUS, 1);
        List<ShareStock> shareStockList = shareStockService.list(stockWrapper);
        if (shareStockList.size() == 0) {
            return;
        }

        try {
            for (int i = 0; i < 3; i++) {

                int year = thisYear - i-1;
                redisTemplate.opsForValue().getOperations().delete(RedisKey.SHARE_FINANCIAL_YEAR+year);
                List<ShareFinancialYear> yearList = shareFinancialYearService.getByYear(year);
                Map<Long,ShareFinancialYear> searchMap= new HashMap<>(4000);
                for (ShareFinancialYear shareFinancialYear : yearList) {
                    searchMap.put(shareFinancialYear.getStockId(),shareFinancialYear);
                }
                if(yearList== null|| yearList.size()==0){
                    return ;
                }
                //三年内的年度财报数据存入redis中
                CountDownLatch latch = new CountDownLatch(shareStockList.size());
                for (ShareStock shareStock : shareStockList) {
                    ThreadUtil.execute(new AbstractJob(shareStock) {

                        @Override
                        public void execute() {
                            ShareFinancialYear shareFinancialYearServiceByYear = searchMap.get(shareStock.getId());
                            if (shareFinancialYearServiceByYear != null) {
                                shareFinancialYearServiceByYear.setId(null);
                                redisTemplate.opsForSet().add(RedisKey.SHARE_FINANCIAL_YEAR + year, JSONObject.toJSONString(shareFinancialYearServiceByYear));
                            } else {
                                undata.incrementAndGet();
                            }
                            latch.countDown();
                        }
                    });//线程
                }
                try {
                    latch.await();
                } catch (Exception e) {
                    log.info("pushLastDayKToRedis 报错了{} ", e);
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {

        } finally {


        }
    }
}
